# vPresent is an immersive presentation creation and display application.
# Copyright (C) 2007-2009 by Priority 5 Holdings, Inc.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

import gui.cluster.builder
import gui.util.mixins


class Environment(gui.util.mixins.Singleton):
   '''
   Global operating environment for vPresent. This class implements the
   Singleton pattern. The reference can be obtained by calling the constructor
   for this class. The properties of this class are the following:

   settings:    A collection of settings/preferences defining (primarily)
                behavioral aspects of the vPresent GUI. The type of this
                object is gui.util.settings.Settings.
   cmdOpts:     An object that holds the command line options as returned by
                optparse.OptionParser.parse_args().
   fileFilters: A list of file filters suitable for use with instances of
                QtGui.QFileDialog. This list represents the file types
                supported by vPresent.
   docHandlers: A dictionary mapping a MIME type to a class that can manage
                operations on documents of that type.
   '''

   def __init__(self):
      if not hasattr(self, '_init_called'):
         self._init_called = True
         self.settings     = None
         self.ribbonMgr    = None
         self.cmdOpts      = None
         self.fileFilters  = []
         self.docTypes     = []
         self.curDocument  = None
         # Store the location of the last directory used for file browsing.
         self.fileStartDir = ''
         self.imageExtensions = None    # Valid image extensions.

   def init(self, settings, ribbonMgr, opts = None):
      self.settings = settings
      self.ribbonMgr = ribbonMgr
      self.cmdOpts  = opts
      builder       = gui.cluster.builder.SettingsBuilder(settings)
      self.cluster  = builder.build()

   def getSettings(self):
      return self.settings

   def getCluster(self):
      return self.cluster

   def registerDocType(self, docType):
      self.docTypes.append(docType)

   def getDocTypes(self):
      return self.docTypes

   def getDocReaderClassForExt(self, extension):
      '''
      Returns the reader class used for reading documents of the given type
      (identified by file extension).
      '''
      if extension.startswith('.'):
         extension = extension[1:]

      for t in self.docTypes:
         if extension in t.getExtensions():
            return t.getReaderClass()

      raise ValueError("Unknown extenstion %s" % extension)

   def getDocWriterClassForExt(self, extension):
      '''
      Returns the writer class used for creating documents of the given type
      (identified by file extension).
      '''
      if extension.startswith('.'):
         extension = extension[1:]

      for t in self.docTypes:
         if extension in t.getExtensions():
            return t.getWriterClass()

      raise ValueError("Unknown extenstion %s" % extension)

   def getDocReaderClassForMimeType(self, mimeType):
      '''
      Returns the reader class used for reading documents of the given type
      (identified by MIME type).
      '''
      for t in self.docTypes:
         if mimeType in t.getMimeTypes():
            return t.getReaderClass()

      raise ValueError("Unknown MIME type %s" % mimeType)

   def getDocWriterClassForMimeType(self, mimeType):
      '''
      Returns the writer class used for creating documents of the given type
      (identified by MIME type).
      '''
      for t in self.docTypes:
         if mimeType in t.getMimeTypes():
            return t.getWriterClass()

      raise ValueError("Unknown MIME type %s" % mimeType)

   def getValidImageExtensions(self):
      """
      Query OpenSG for all valid image extentions.
      NOTE: This would be much better if we could map
            FileType name to extention list.
      """
      if self.imageExtensions is None:
         import osg2 as osg
         ifh = osg.ImageFileHandler.the()
         mime_strs = ["All Files (*)"]
         for (mimetype, ift) in ifh.getMimeTypeMap().iteritems():
            suffix_list = ift.getSuffixList()
            mime_str = "%s ("%mimetype + " ".join(["*.%s"%sf for sf in suffix_list]) + ")"
            mime_strs.append(mime_str)
         self.imageExtensions = ";;".join(mime_strs)
      return self.imageExtensions
